Location Based Searches In Drupal7

This is the simple example of how to find the contents based on latitude and longitude from a certain distance.

This is based on node and the fields latitude and longitude. We can implement this on using custom tables or entities other than node. Eg: users

Create a node type offer. Create two text fields latitude and longitude. 

Use the following function in your module to get the nodes based on distance. 

function getContentsinBoundary($latitude,  $longitude, $distance=100){

$query = db_select('node', 'n');

$query->leftjoin('field_data_field_latitude', 'la', 'la.entity_id = n.nid');

$query->leftjoin('field_data_field_longitude', 'lg', 'lg.entity_id = n.nid');

$query->fields('n', array('title', 'nid')) ->fields('la', array('field_latitude_value')) ->fields('lg', array('field_longitude_value')) ->condition('n.type', 'offer');

//Range /* * 6371 radius of earth in km = 3959 miles * refer: Haversine formula https://developers.google.com/maps/articles/phpsqlsearch_v3?csw=1 */

$query->addExpression('( 6371 * acos( cos( radians('.$latitude.') ) * cos( radians( la.field_latitude_value ) ) * cos( radians( lg.field_longitude_value ) - radians('.$longitude.') ) + sin( radians('.$latitude.') ) * sin( radians( la.field_latitude_value ) ) ) )','distance');

$query->havingCondition('distance', $distance,'<=');

$result = $query->orderby('n.nid', 'DESC')->execute()->fetchAll();

}

$contents = getContentsinBoundary($latitude = '9.946438', $longitude = '76.272946', $distance=50);

The above call will get the contents around 50 kms in Cochin area.